import { defineStore } from 'pinia'
import {IloginForm,IResponseData, ILoginResponse  } from './userType'
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from '@/utils/token'
import { login, logout, getUserInfo } from '@/api/user'
import { filterAsyncRoute } from '@/utils'
import { constantRoute, asnycRoute } from '@/router/routers'
import router from '@/router/index' 
import { cloneDeep } from 'lodash'
// UserStore
export const useUserStore = defineStore("User", {
    state: () => {
        return {
            menuRoutes: [...asnycRoute],
            token: GET_TOKEN(),
            username: '',
            avatar: '',
            buttons: []
        }
    },
    // 请求数据
    actions: {
        async userLogin(data: IloginForm) {
            // 登录请求
            const result: ILoginResponse = await login(data);
            if(result.code == 200) {
                // 表示为成功了
                // 设置token
                SET_TOKEN(result.data)
            } else {
                // 发生错误
                return Promise.reject(new Error(result.data))
            }
            
        },
        async userLogout() {
            //调用接口去除
            const result: IResponseData = await logout();
            if(result.code == 200) {
                // 去除token
                REMOVE_TOKEN()
                this.avatar = ''
                this.buttons = []
                this.username = ''

                return 'ok'
            }else {
                return Promise.reject(new Error(result.data))
            }
        },
        async userInfo() {
            const result: IResponseData = await getUserInfo()
            if(result.code == 200) {
                this.username = result.data.name
                this.avatar = result.data.avatar
                this.buttons = result.data.buttons

                const userAsyncRoute = filterAsyncRoute(
                    asnycRoute,//cloneDeep(asnycRoute),
                    result?.data.routes,
                  )
                  //菜单需要的数据整理完毕
         
                this.menuRoutes = [...constantRoute, ...userAsyncRoute]
                
                userAsyncRoute.forEach((route: any) => {
                router.addRoute(route)
                })
                return 'ok'
            } else {
                return Promise.reject(new Error(result.data))
            }
        }
    }
})